<?php


namespace app\services\utils;


use think\cache\driver\Redis;
use think\facade\Config;

class RedisService extends Redis {
    /**
     * 实例化的对象,单例模式.
     * @var Redis
     */
    protected static $instance = [];
    protected $db = 8;

    /**
     * 私有的构造函数 禁止直接实例化
     * RedisService constructor.
     * @param $db
     */
    private function __construct($db) {
        $options = Config::get('cache.stores.redis');

        $options['select'] = $db;

        $this->db = $db;

        $this->options = array_merge($this->options, $options);

        parent::__construct();
    }

    /**
     * 提供对外实例化方法
     * @param int $db
     * @return mixed
     */
    public static function instance($db = 8) {
        if (!isset(self::$instance[$db])) {

            self::$instance[$db] = new self($db);

        }
        return self::$instance[$db];
    }

    /**
     * 禁止clone
     */
    private function __clone() {
    }

    /**
     * 析构函数
     */
    public function __destruct() {
        self::$instance[$this->db]->close();
        unset(self::$instance[$this->db]);
    }
}